<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <page-tools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 {{ total }} 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button v-power="'import'" type="danger" size="small" @click="uploadExcel">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="exportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employeesList" stripe :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{ row }">
              <ImageHolder :src="row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" sortable :sort-method="workNumberSortFn" />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatter" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable :formatter="timeFormatter" />
          <el-table-column label="操作" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}?form=${row.formOfEmployment}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoleFn(row)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="closeFn">
        <EmpForm ref="empForm" :show-dialog.sync="showDialog" :tree-data="treeData" @addEmpEV="addEmpFn" />
      </el-dialog>
      <!-- 员工-分配角色权限 - 弹窗 -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog">
        <!-- 设置角色组件 -->
        <assign-role-dialog ref="assignRoleRef" :show.sync="showRoleDialog" :role-list="roleList" @addRoleEV="addRoleFn" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeListAPI, departmentsListAPI, transTree, addEmployeeAPI,
  delEmployeeAPI, getRolesAPI, getUserDetailByIdAPI, assignRolesAPI } from '@/api'
import Employees from '@/api/constant'
import dayjs from 'dayjs'
import EmpForm from './components/empForm.vue'
import AssignRoleDialog from './components/assignRoleDialog.vue'

export default {
  name: 'Employees',
  components: {
    EmpForm,
    AssignRoleDialog
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10 // 每页条数
      },
      employeesList: [],
      total: 0,
      hireType: Employees.hireType,
      showDialog: false, // 添加员工组件的展示
      treeData: [],
      showRoleDialog: false,
      roleList: [],
      clickEmpId: ''
    }
  },
  created() {
    this.getEmployeeList()
    this.getDepartments()
    this.getRoleList()
  },
  methods: {
    async getDepartments() {
      const res = await departmentsListAPI()
      if (!res.success) return this.$message.error(res.message)
      this.treeData = transTree(res.data.depts, '')
    },
    // 格式化表格的某一项
    formatter(row, column, cellValue, index) {
      // 用数组的 find 方法找到 id = 1 的元素，再取出它的 value
      const obj = Employees.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    timeFormatter(row, column) {
      return dayjs(row.timeOfEntry).format('YYYY-MM-DD')
    },
    // 排序
    workNumberSortFn(a, b) {
      return parseInt(a.workNumber) - parseInt(b.workNumber)
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(val) {
      this.query.size = val
      this.getEmployeeList()
    },
    // 当前页面发生改变时触发
    handleCurrentChange(val) {
      this.query.page = val
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeListAPI(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    async getRoleList() {
      const res1 = await getRolesAPI({ page: 1, pagesize: 5 })
      const res = await getRolesAPI({ page: 1, pagesize: res1.data.total })
      this.roleList = res.data.rows
    },

    // 添加员工
    async addEmpFn(empForm) {
      const res = await addEmployeeAPI(empForm)
      if (res.success) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
      this.getEmployeeList()
    },

    closeFn() {
      this.$refs.empForm.$refs.addForm.resetFields()
    },

    // 删除员工
    delEmp(row) {
      this.$confirm('确定删除该员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployeeAPI(row.id)
        if (res.success) {
          if (this.employeesList.length === 1 && this.query.page > 1) {
            this.query.page--
          }
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.getEmployeeList()
      })
    },

    // 导入excel
    uploadExcel() {
      this.$router.push('/excel')
    },

    transData(rows) {
      const headerArr = ['序号', '姓名', '头像', '手机号', '工号', '聘用形式', '部门', '入职时间']
      // 4.1 数据key的映射关系(思路: 遍历上边数组里按照顺序, 取出中文的名字, 但是对应数组值的数组, 要从英文key对象中取出value值, 我要用中文key换到英文key然后去取到值)
      const myObj = {
        // 序号可以等遍历的时候直接用索引值, 而不是来自于英文对象里
        '姓名': 'username',
        '头像': 'staffPhoto',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName',
        '入职时间': 'timeOfEntry'
      }
      // 4.2 按照顺序, 形成值的数组 (明确目标->想要数据结构->读代码(每个变量意思)读2-3遍->仿写3-5遍)
      const resultArr = rows.map((item, index) => {
        const valueArr = [] // 值小数组
        headerArr.forEach(zhKey => {
          if (zhKey === '序号') {
            valueArr.push(index + 1)
          } else {
            const enKey = myObj[zhKey]
            valueArr.push(item[enKey])
          }
        })
        return valueArr
      })

      return { header: headerArr, data: resultArr }
    },

    // 导出excel
    async exportExcel() {
      this.query.size = this.total
      const res = await getEmployeeListAPI(this.query)
      const excelObj = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工列表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // 分类角色
    async assignRoleFn(empObj) {
      this.clickEmpId = empObj.id
      const res = await getUserDetailByIdAPI(empObj.id)
      this.showRoleDialog = true
      this.$nextTick(() => {
        this.$refs.assignRoleRef.checkList = [...res.data.roleIds]
      })
    },

    async addRoleFn(roleIdsList) {
      const res = await assignRolesAPI({
        id: this.clickEmpId,
        roleIds: roleIdsList
      })
      if (res.success) {
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
